package com.gx.cn.hospitalmanage.Fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.gx.cn.hospitalmanage.HospitalManage.HospitalRegistraActivity;
import com.gx.cn.hospitalmanage.HospitalManage.OutPatientPaymentActivity;
import com.gx.cn.hospitalmanage.HospitalManage.PatientTransferZoneActivity;
import com.gx.cn.hospitalmanage.HospitalManage.PatientinforationActivity;
import com.gx.cn.hospitalmanage.MainActivity;
import com.gx.cn.hospitalmanage.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


/**
 * Created by JCQ on 2017/9/27.
 */

public class MyFragment1 extends Fragment{

    private View mView;
    private ViewPager mViewPaper;
    private List<ImageView> images;
    private List<View> dots;
    private int currentItem;
    //记录上一次点的位置
    private int oldPosition = 0;
    //存放图片的id
    private int[] imageIds = new int[]{
            R.drawable.yy1,
            R.drawable.yy2,
            R.drawable.yy3,
            R.drawable.yy4,
            R.drawable.yy5,
    };
    //存放图片的标题
    private String[] titles = new String[]{
            "1",
            "2",
            "3",
            "4",
            "5"
    };

    private TextView title;
    private ViewPagerAdapter adapter;
    private ScheduledExecutorService scheduledExecutorService;


    //定义图标数组
    private int[] imageRes = {
            R.drawable.btn_eigth,
            R.drawable.btn_ten,
            R.drawable.btn_nigth,
            R.drawable.btn_threeth,
            R.drawable.btn_four,
            R.drawable.btn_tenone,
            R.drawable.btn_seven,
            R.drawable.btn_six,
            R.drawable.btn_free};

    //定义图标下方的名称数组
    private String[] name = {
            "入院登记",
            "病人信息",
            "病人转区",
            "门诊缴费",
            "住院信息",
            "出院账单",
            "费用查询",
            "电子病历",
            "更多"
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        mView=inflater.inflate(R.layout.fg_one_content, null);
        setView();
        return mView;

    }



    private void setView(){

        //轮播图
        mViewPaper = (ViewPager)mView.findViewById(R.id.vp);

        //显示的图片
        images = new ArrayList<ImageView>();
        for(int i = 0; i < imageIds.length; i++){
            ImageView imageView = new ImageView(getActivity());
            imageView.setBackgroundResource(imageIds[i]);
            images.add(imageView);
        }
        //显示的小点
        dots = new ArrayList<View>();
        dots.add(mView.findViewById(R.id.dot_0));
        dots.add(mView.findViewById(R.id.dot_1));
        dots.add(mView.findViewById(R.id.dot_2));
        dots.add(mView.findViewById(R.id.dot_3));
        dots.add(mView.findViewById(R.id.dot_4));

        title = (TextView) mView.findViewById(R.id.title);
        title.setText(titles[0]);

        adapter = new ViewPagerAdapter();
        mViewPaper.setAdapter(adapter);

        mViewPaper.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {


            @Override
            public void onPageSelected(int position) {
                title.setText(titles[position]);
                dots.get(position).setBackgroundResource(R.mipmap.indicator_selected);
                dots.get(oldPosition).setBackgroundResource(R.mipmap.indicator_nor);

                oldPosition = position;
                currentItem = position;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

       // 九宫格按钮
        GridView gridView=(GridView) mView.findViewById(R.id.gridview);//初始化

        //生成动态数组，并且转入数据
        ArrayList<HashMap<String ,Object>> listItemArrayList=new ArrayList<HashMap<String,Object>>();
        for(int i=0; i<imageRes.length; i++){
            HashMap<String, Object> map=new HashMap<String,Object>();
            map.put("itemImage", imageRes[i]);
            map.put("itemText", name[i]);
            listItemArrayList.add(map);
        }
        //生成适配器的ImageItem 与动态数组的元素相对应
        SimpleAdapter saImageItems = new SimpleAdapter(getActivity(),
                listItemArrayList,//数据来源
                R.layout.fg_one_viewpager,//item的XML

                //动态数组与ImageItem对应的子项
                new String[]{"itemImage", "itemText"},

                //ImageItem的XML文件里面的一个ImageView,TextView ID
                new int[]{R.id.img_shoukuan, R.id.txt_shoukuan});
        //添加并且显示
        gridView.setAdapter(saImageItems);
        //添加消息处理
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //显示消息
                Toast.makeText(getActivity(),name[position],Toast.LENGTH_LONG).show();

                //入院登记
                 int index=position+1;//id是从0开始的，所以需要+1
                  if(index==1){
                      Intent intent=new Intent();
                      intent.setClass(getActivity(), HospitalRegistraActivity.class);
                      startActivity(intent);
                  }

                  //病人信息
                  if(index==2){

                      Intent intent=new Intent();
                      intent.setClass(getActivity(), PatientinforationActivity.class);
                      startActivity(intent);
                  }

                  //病人转区
                if(index==3){

                    Intent intent=new Intent();
                    intent.setClass(getActivity(), PatientTransferZoneActivity.class);
                    startActivity(intent);
                }

                //门诊缴费
                if(index==4){

                    Intent intent=new Intent();
                    intent.setClass(getActivity(), OutPatientPaymentActivity.class);
                    startActivity(intent);
                }


            }
        });
    }

    /*定义的适配器*/
    public class ViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return images.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup view, int position, Object object) {
            // TODO Auto-generated method stub
//          super.destroyItem(container, position, object);
//          view.removeView(view.getChildAt(position));
//          view.removeViewAt(position);
            view.removeView(images.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            // TODO Auto-generated method stub
            view.addView(images.get(position));
            return images.get(position);
        }

    }

    /**
     * 利用线程池定时执行动画轮播
     */
    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(
                new ViewPageTask(),
                2,
                2,
                TimeUnit.SECONDS);
    }


    /**
     * 图片轮播任务
     * @author liuyazhuang
     *
     */
    private class ViewPageTask implements Runnable{

        @Override
        public void run() {
            currentItem = (currentItem + 1) % imageIds.length;
            mHandler.sendEmptyMessage(0);
        }
    }

    /**
     * 接收子线程传递过来的数据
     */
    private Handler mHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            mViewPaper.setCurrentItem(currentItem);
        };
    };

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        if(scheduledExecutorService != null){
            scheduledExecutorService.shutdown();
            scheduledExecutorService = null;
        }
    }



}
